import { downImageByUrl } from '@/hooks/down'
import { addCollect } from '@/api/imgRecord'
import { toast } from '@/uni_modules/uv-ui-tools/libs/function/index.js';
import { notAuthToast } from '@/hooks/common'
import sharePages from '@/framework/plugins/sharePages'
import { getImageListCache } from '@/hooks/common'
export default {
	mixins: [sharePages],
	data() {
		return {
			fileId: '',
			imgUrl: '',
			downUrl: '',
			imageList: [],
			showPrevButton: false,
			showNextButton: false,
			currentIndex: 0,
			imageDataList: []
		}
	},
	props: {
		options: {}
	},
	computed: {
		imageUrlList(){
			return this.imageList.map(fileId => {
				if(fileId?.startsWith('http')){
					return fileId
				}
				return this.$config.replacehUrl(`imgStore/openApi/previewByBussId?bussid=${fileId}&size=medium`)
			})
		}
	},
	watch: {
		imageUrlList(val){
			this.initImageDataList()
		}
	},
	methods: {
		goToPage(url){
			uni.navigateTo({
			  url: url 
			});
		},
		checkLogin(){
			const token = uni.getStorageSync("token");
			if(!token){
				notAuthToast()
				this.goToPage('/pages/login/index')
				return false
			}
			return true
		},
		send(url){
			if(!this.checkLogin()){
				return
			}
			url = this.downUrl
			// 分享的图片的链接
			wx.downloadFile({
				url: url,
				success: (res) => {
				  wx.showShareImageMenu({
					path: res.tempFilePath
				  })
				}
			})
		},
		async down(url){
			if(!this.checkLogin()){
				return
			}
			url = this.downUrl
			uni.showLoading({title: '下载中...',mask: true})
			await downImageByUrl(url).catch(e => {
				uni.hideLoading();
			})
			uni.hideLoading();
		},
		async collect(){
			if(!this.checkLogin()){
				return
			}
			const res = await addCollect({ businid: this.fileId })
			if(res.code == 200 && res.msg){
				toast(res.msg)
			}
		},
		initImageDataList() {
		  this.imageDataList = this.imageUrlList.map((url, index) => {
			// 只有当前索引对应的图片设置真实链接，其他设置为空
			return {
			  src: index === this.currentIndex ? url : '',
			  originalSrc: url
			};
		  });
		  
		  // 异步获取图片宽高并更新 mode
		  this.imageDataList.forEach((item, index) => {
			uni.getImageInfo({
			  src: item.originalSrc,
			  success: (res) => {
				this.imageDataList[index].mode = res.width > res.height? 'widthFix' : 'aspectFill';
			  },
			  fail: (err) => {
				console.error('获取图片信息失败:', err);
			  }
			});
		  });
		},
		onSwiperChange(e) {
		  // 获取当前滑动到的索引
		  this.currentIndex = e?.detail?.current;
		  // 更新对应图片的 src 属性
		  this.imageDataList = this.imageDataList.map((item, index) => {
			return {
			  src: index === this.currentIndex ? item.originalSrc : '',
			  originalSrc: item.originalSrc
			};
		  });
		   this.updateImageUrls();
		},
		init(fileId, imageList) {
			this.fileId = fileId;
			const cacheImageList = getImageListCache()
			const alImageList = cacheImageList
			this.imageList = (!alImageList || alImageList.length === 0) ? [fileId] : alImageList;
			this.currentIndex = this.imageList.findIndex(item => item === fileId);
			this.updateImageUrls();
		},
		showToast(message){
			return uni.showToast({
				title: message,
				duration: 3000,
				icon: 'none'
			});
		},
		updateImageUrls() {
			this.fileId = this.imageList[this.currentIndex];
			this.downUrl = this.fileId?.startsWith('http') ?this.fileId : this.$config.replacehUrl(`imgStore/storeFile/downByBussId?bussid=${this.fileId}`);
			this.imgUrl = this.fileId?.startsWith('http') ?this.fileId :  this.$config.replacehUrl(`imgStore/openApi/previewByBussId?bussid=${this.fileId}&size=medium`);
		},
		goBack(){
			uni.navigateBack({
				delta: 1 
			});
		},
		initData(options){
			const encodedFileId = options.fileId;
			// 对编码后的 fileId 进行反编码
			const fileId = decodeURIComponent(encodedFileId);
			const imageList = options?.imageList ? JSON.parse(options.imageList) : [];
			this.init(fileId, imageList);
		}
	},
	mounted(){
		this.initData(this.options)
	},
	// onLoad(options){
	// 	debugger
	// 	this.initData(options)
	// }
}